package ctrl

import (
	"fmt"
	"im/util"
	"io"
	"log"
	"math/rand"
	"net/http"
	"os"
	"path"
	"strings"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

const (
	AccessKeyId     = "5p2RZKnrUanMuQw9"
	AccessKeySecret = "bsNmjU8Au08axedV40TRPCS5XIFAkK"
	EndPoint        = "oss-cn-shenzhen.aliyuncs.com"
	Bucket          = "winliondev"
)

func init() {
	err := os.MkdirAll("./mnt", os.ModePerm)
	log.Println("mkdir", err)
}

func Upload(w http.ResponseWriter, r *http.Request) {
	UploadLocal(w, r)
}

func UploadLocal(w http.ResponseWriter, r *http.Request) {
	// 获取上传文件
	srcFile, head, err := r.FormFile("file")
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	// 创建新文件
	suffix := ".png"
	// 如果源文件包含后缀
	ofilename := head.Filename
	if path.Ext(ofilename) != "" {
		suffix = path.Ext(ofilename)
	}
	// 如果指定了文件类型
	if len(r.FormValue("filetype")) > 0 {
		suffix = r.FormValue("filetype")
	}
	filename := fmt.Sprintf("%d%04d%s", time.Now().Unix(), rand.Int31(), suffix)
	dstFile, err := os.Create("./mnt/" + filename)
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	// 将源文件内容复制到新文件
	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	url := "/mnt/" + filename
	util.Resp(w, 200, "suc", url)
}

// oss上传
func UploadOss(w http.ResponseWriter, r *http.Request) {
	// 获得上传的文件
	srcFile, head, err := r.FormFile("file")
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	// 获得文件后缀.png/.mp3
	suffix := ".png"
	// 如果前端文件名称包含后缀 xx.xx.png
	ofilename := head.Filename
	tmp := strings.Split(ofilename, ".")
	if len(tmp) > 1 {
		suffix = "." + tmp[len(tmp)-1]
	}
	// 如果前端指定filetype
	filetype := r.FormValue("filetype")
	if len(filetype) > 0 {
		suffix = filetype
	}
	// 初始化ossclient
	client, err := oss.New(EndPoint, AccessKeyId, AccessKeySecret)
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	// 获得bucket
	bucket, err := client.Bucket(Bucket)
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	filename := fmt.Sprintf("mnt/%d%04d%s",
		time.Now().Unix(), rand.Int31(),
		suffix)
	// 通过bucket上传
	err = bucket.PutObject(filename, srcFile)
	if err != nil {
		util.Resp(w, -1, err.Error(), nil)
		return
	}
	url := "http://" + Bucket + "." + EndPoint + "/" + filename
	util.Resp(w, 0, url, nil)
}
